﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Collections;
using System.Data;

namespace ReportS
{
    /// <summary>
    /// 营业额.xaml 的交互逻辑
    /// </summary>
    public partial class 营业额 : Window
    {
        public 营业额()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }

        private void InitVar()
        {
            uCdataGrid1.TableText = DataTableText.营业额;

            checkComboBoxUserS.DisplayMemberPath = "Name";
            checkComboBoxUserS.ValueMemberPath = "Id";
            checkComboBoxUserS.ItemsSource = Table.UserS.GetList(null, Table.UserS.EnumFlag.经办人);

            checkComboBoxCorS.DisplayMemberPath = "Name";
            checkComboBoxCorS.ValueMemberPath = "Id";
            checkComboBoxCorS.ItemsSource = MainWindow.allCorS;

            checkComboBoxOrderType.Items.Add("批发销售");
            checkComboBoxOrderType.Items.Add("POS零售");
            checkComboBoxOrderType.Items.Add("售后维护");
            checkComboBoxOrderType.Items.Add("客户返修");

        }

        List<TempClass> tc = new List<TempClass>();
        private void InitEvent()
        {
            buttonOK.Click += (ss, ee) =>
                {
                    List<TempClass> tc = new List<TempClass>();
                    List<TempClass> result = new List<TempClass>();

                    if (string.IsNullOrEmpty(checkComboBoxOrderType.Text) || checkComboBoxOrderType.Text.Contains("批发销售"))
                        tc.AddRange(GetSalesOrderS());
                    if (string.IsNullOrEmpty(checkComboBoxOrderType.Text) || checkComboBoxOrderType.Text.Contains("POS零售"))
                        tc.AddRange(GetPOS());
                    if (string.IsNullOrEmpty(checkComboBoxOrderType.Text) || checkComboBoxOrderType.Text.Contains("售后维护"))
                        tc.AddRange(GetShouHou());
                    if (string.IsNullOrEmpty(checkComboBoxOrderType.Text) || checkComboBoxOrderType.Text.Contains("客户返修"))
                        tc.AddRange(GetFanXiu());

                    if (checkBoxShowSum.IsChecked.Value)
                    {
                        foreach (TempClass t in tc.Distinct(new DoubleH.Utility.NormalUtility.Compare<TempClass>((x, y) => (null != x && null != y) && (x.CorSName.Equals(y.CorSName)))))
                        {
                            var vr = tc.Where(f => f.CorSName == t.CorSName);
                            result.Add(new TempClass()
                            {
                                CorSName = t.CorSName,
                                YingYeE = vr.Sum(f => f.YingYeE),
                                MaoLi = vr.Sum(f => f.MaoLi)
                            });
                        }
                        foreach (TempClass t in tc.Distinct(new DoubleH.Utility.NormalUtility.Compare<TempClass>((x, y) => (null != x && null != y) && (x.UserSName.Equals(y.UserSName)))))
                        {
                            var vr = tc.Where(f => f.UserSName == t.UserSName);
                            result.Add(new TempClass()
                            {
                                UserSName = t.UserSName,
                                YingYeE = vr.Sum(f => f.YingYeE),
                                MaoLi = vr.Sum(f => f.MaoLi)
                            });
                        }
                    }
                    else
                        result = tc;

                    if (checkBoxHideZero.IsChecked.Value)
                       result=new List<TempClass>( result.Where(f => f.MaoLi != 0 && f.YingYeE != 0));

                    uCdataGrid1.Init(result, new UC.CharProperty() { ValueTitle = "营业额", ValueName = "YingYeE", Series = new System.Windows.Controls.DataVisualization.Charting.LineSeries() },
                            new UC.CharProperty() { ValueTitle = "毛利", ValueName = "MaoLi", Series = new System.Windows.Controls.DataVisualization.Charting.LineSeries() });
                };
        }



        private List<TempClass> GetSalesOrderS()
        {
            List<TempClass> tc = new List<TempClass>();
            StringBuilder sb = new StringBuilder();
            sb.Append("select Result1.*,UserS.Name as UserSName from (select ProductSIO.*,SalesOrderS.UserSId as posUserId, CorS.Name as CorSName from ProductSIO");
            sb.Append(" left join CorS on ProductSIO.CorSId=CorS.Id  left join SalesOrderS on SalesOrderS.OrderNO like ProductSIO.OrderNO  ");
            sb.Append(" where ProductSIO.Enable=1 and ProductSIO.OrderNO like 'PF%' ");
            sb.Append(" and cast(ProductSIO.OrderDateTime as varchar) >=" + uCDateTime1.StartDateTimeString + " and cast(ProductSIO.OrderDateTime as varchar) <=" + uCDateTime1.EndDateTimeString);
            if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
            {
                sb.Append(" and (");
                foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
                    sb.Append(" ProductSIO.CorSId=" + str + " or ");

                sb.Remove(sb.Length - 3, 3);
                sb.Append(")");
            }
            if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
            {
                sb.Append(" and (");
                foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
                    sb.Append(" posUserId=" + str + " or ");

                sb.Remove(sb.Length - 3, 3);
                sb.Append(")");
            }
            sb.Append(") as Result1 left join UserS on UserS.Id=posUserId");
            foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows(sb.ToString()))
            {
                TempClass t = new TempClass();
                t.CorSName = row["CorSName"] as string;
                t.UserSName = row["UserSName"] as string;
                t.YingYeE = (double)row["WholesalePrice"] * (double)row["Quantity"];
                t.MaoLi = t.YingYeE - (double)row["AveragePrice"] * (double)row["Quantity"];
                tc.Add(t);
            }

            return tc;
            // if (string.IsNullOrEmpty(checkComboBoxUserS.SelectedValue) && string.IsNullOrEmpty(checkComboBoxCorS.SelectedValue))
            // {
            //     MessageWindow.Show("请选择经办人或者客商");
            //     return;
            // }

            // tc.Clear();
            // StringBuilder sb = new StringBuilder(" where Enable=1 and Flag=1");
            // if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
            // {
            //     sb.Append("(");
            //     foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
            //         sb.Append(" UserSId=" + str + " or ");

            //     sb.Remove(sb.Length - 3, 3);
            //     sb.Append(")");
            // }

            // if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
            // {
            //     sb.Append("(");
            //     foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
            //         sb.Append(" CorSId=" + str + " or ");

            //     sb.Remove(sb.Length - 3, 3);
            //     sb.Append(")");
            // }
            // IList il=new Table.PayS().GetListByWhere("");
            //IEnumerable<Table.PayS> ii= Enumerable.Cast<Table.PayS>(il);


            //List<UC.CharProperty> cp=new List<UC.CharProperty>();
            //if (!string.IsNullOrEmpty(checkComboBoxUserS.SelectedValue))
            //{
            //    foreach (string str in checkComboBoxUserS.Text.Split(','))
            //        cp.Add(new UC.CharProperty()
            //        {
            //            Series = new System.Windows.Controls.DataVisualization.Charting.ColumnSeries(),
            //            ValueName = "Name",
            //            ValueTitle = "经办人"
            //        });
            //}
            //else
            //    foreach (string str in checkComboBoxCorS.Text.Split(','))
            //        cp.Add(new UC.CharProperty()
            //        {
            //            Series = new System.Windows.Controls.DataVisualization.Charting.ColumnSeries(),
            //            ValueName = "Name",
            //            ValueTitle = "客商"
            //        });


            //uCdataGrid1.Init(tc, cp.ToArray());

            return tc;
        }

        private List<TempClass> GetPOS()
        {
            List<TempClass> tc = new List<TempClass>();
            StringBuilder sb = new StringBuilder();
            sb.Append("select Result1.*,UserS.Name as UserSName from (select ProductSIO.*,PosOrderS.UserSId as posUserId, CorS.Name as CorSName from ProductSIO");
            sb.Append(" left join CorS on ProductSIO.CorSId=CorS.Id  left join PosOrderS on PosOrderS.OrderNO like ProductSIO.OrderNO  ");
            sb.Append(" where ProductSIO.Enable=1 and ProductSIO.OrderNO like 'POS%' ");
            sb.Append(" and cast(ProductSIO.OrderDateTime as varchar) >=" + uCDateTime1.StartDateTimeString + " and cast(ProductSIO.OrderDateTime as varchar) <=" + uCDateTime1.EndDateTimeString);
            if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
            {
                sb.Append(" and (");
                foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
                    sb.Append(" ProductSIO.CorSId=" + str + " or ");

                sb.Remove(sb.Length - 3, 3);
                sb.Append(")");
            }
            if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
            {
                sb.Append(" and (");
                foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
                    sb.Append(" posUserId=" + str + " or ");

                sb.Remove(sb.Length - 3, 3);
                sb.Append(")");
            }
            sb.Append(") as Result1 left join UserS on UserS.Id=posUserId");
            foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows(sb.ToString()))
            {
                TempClass t = new TempClass();
                t.CorSName = row["CorSName"] as string;
                t.UserSName = row["UserSName"] as string;
                t.YingYeE = (double)row["WholesalePrice"] * (double)row["Quantity"];
                t.MaoLi = t.YingYeE - (double)row["AveragePrice"] * (double)row["Quantity"];
                tc.Add(t);
            }

            return tc;
        }

        private List<TempClass> GetShouHou()
        {
            /*
             * 必须是回访结束后才计算，因为可能员工不老实啊。
            *毛利=核实后的收费-区域补偿费
             */
            
            List<TempClass> tc = new List<TempClass>();
            StringBuilder sb = new StringBuilder();
            sb.Append("select AfterSaleServiceS.FuWuFeiHeShi,AfterSaleServiceS.ServiceUserS , CorS.Name as CorSName from AfterSaleServiceS");
            sb.Append(" left join CorS on AfterSaleServiceS.CorSId=CorS.Id   ");
            sb.Append(" where AfterSaleServiceS.Enable>2   ");
            sb.Append(" and cast(AfterSaleServiceS.WanChengDateTime as varchar) >=" + uCDateTime1.StartDateTimeString + " and cast(AfterSaleServiceS.WanChengDateTime as varchar) <=" + uCDateTime1.EndDateTimeString);
            if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
            {
                sb.Append(" and (");
                foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
                    sb.Append(" AfterSaleServiceS.CorSId=" + str + " or ");

                sb.Remove(sb.Length - 3, 3);
                sb.Append(")");
            }
            if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
            {
                sb.Append(" and (");
                foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
                    sb.Append(" posUserId=" + str + " or ");

                sb.Remove(sb.Length - 3, 3);
                sb.Append(")");
            }
            foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows(sb.ToString()))
            {
                TempClass t = new TempClass();
                t.CorSName = row["CorSName"] as string;
                //t.UserSName = row["UserSName"] as string;
                t.YingYeE = (double)row["FuWuFeiHeShi"];
                //t.MaoLi = t.YingYeE - (double)row["AveragePrice"] * (double)row["Quantity"];
                tc.Add(t);
            }
            return tc;
        }

        private List<TempClass> GetFanXiu()
        {
            List<TempClass> tc = new List<TempClass>();
            //StringBuilder sb = new StringBuilder();
            //sb.Append("select Result1.*,UserS.Name as UserSName from (select ProductSIO.*,PosOrderS.UserSId as posUserId, CorS.Name as CorSName from ProductSIO");
            //sb.Append(" left join CorS on ProductSIO.CorSId=CorS.Id  left join PosOrderS on PosOrderS.OrderNO like ProductSIO.OrderNO  ");
            //sb.Append(" where ProductSIO.Enable=1 and ProductSIO.OrderNO like 'POS%' ");
            //sb.Append(" and cast(ProductSIO.OrderDateTime as varchar) >=" + uCDateTime1.StartDateTimeString + " and cast(ProductSIO.OrderDateTime as varchar) <=" + uCDateTime1.EndDateTimeString);
            //if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
            //{
            //    sb.Append(" and (");
            //    foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
            //        sb.Append(" ProductSIO.CorSId=" + str + " or ");

            //    sb.Remove(sb.Length - 3, 3);
            //    sb.Append(")");
            //}
            //if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
            //{
            //    sb.Append(" and (");
            //    foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
            //        sb.Append(" posUserId=" + str + " or ");

            //    sb.Remove(sb.Length - 3, 3);
            //    sb.Append(")");
            //}
            //sb.Append(") as Result1 left join UserS on UserS.Id=posUserId");
            //foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows(sb.ToString()))
            //{
            //    TempClass t = new TempClass();
            //    t.CorSName = row["CorSName"] as string;
            //    t.UserSName = row["UserSName"] as string;
            //    t.YingYeE = (double)row["WholesalePrice"] * (double)row["Quantity"];
            //    t.MaoLi = t.YingYeE - (double)row["AveragePrice"] * (double)row["Quantity"];
            //    tc.Add(t);
            //}

            return tc;
        }
    }

    public class TempClass
    {
        public string CorSName { get; set; }
        public string UserSName { get; set; }
        public double YingYeE { get; set; }
        public double MaoLi { get; set; }
    }
}
